package org.jeecg.glr.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.constant.SysConstant;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.glr.entity.GlrLed;
import org.jeecg.glr.service.IGlrLedService;
import org.jeecg.glr.service.ILedCommon;
import org.jeecg.glr.util.GLRConstant;
import org.jeecg.glr.util.HttpRequestUtil;
import org.jeecg.glr.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: LED屏管理
 * @Author: jeecg-boot
 * @Date: 2020-02-20
 * @Version: V1.0
 */
@RestController
@RequestMapping("/glr/glrLed")
@Slf4j
public class GlrLedController extends JeecgController<GlrLed, IGlrLedService> {
    @Autowired
    private IGlrLedService glrLedService;
    @Value("${glr.url.led_status}")
    private String led_status;
    @Resource
    ILedCommon ledCommon;
    /**
     * 分页列表查询
     *
     * @param glrLed
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @GetMapping(value = "/list")
    public Result<?> queryPageList(GlrLed glrLed,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {

        Map<String, String[]> parameterMap=new HashMap(req.getParameterMap());
        parameterMap.remove(QueryGenerator.ORDER_COLUMN);
        parameterMap.remove(QueryGenerator.ORDER_TYPE);
        QueryWrapper<GlrLed> queryWrapper = QueryGenerator.initQueryWrapperCode(glrLed,parameterMap);
        queryWrapper.orderByAsc("name");
        queryWrapper.orderByAsc("status");
        Page<GlrLed> page = new Page<GlrLed>(pageNo, pageSize);
        IPage<GlrLed> pageList = glrLedService.page(page, queryWrapper);
        List<GlrLed> list = pageList.getRecords();
        for (GlrLed led : list) {
           if(StringUtil.isEmpty(led.getStatus())||led.getStatus().equals(GLRConstant.YN_N)){
               led.setOpenStatus(GLRConstant.YN_N);
               led.setBrightness(0);
           }
        }
        return Result.ok(pageList);
    }
    /**
     * 添加
     *
     * @param glrLed
     * @return
     */
    @AutoLog(value = "添加LED屏",logType= CommonConstant.LOG_TYPE_2)
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody GlrLed glrLed) {
        glrLedService.saveEntity(glrLed);
        return Result.ok("添加成功！");
    }
    /**
     * 编辑
     *
     * @param glrLed
     * @return
     */
    @AutoLog(value = "修改LED屏",logType= CommonConstant.LOG_TYPE_2)
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody GlrLed glrLed) {
        glrLedService.updateEntityById(glrLed);
        return Result.ok("编辑成功!");
    }
    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "删除LED屏",logType= CommonConstant.LOG_TYPE_2)
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        glrLedService.removeEntityById(id);
        return Result.ok("删除成功!");
    }
    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "删除LED屏",logType= CommonConstant.LOG_TYPE_2)
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.glrLedService.removeEntityByIds(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功!");
    }
    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        GlrLed glrLed = glrLedService.getById(id);
        if (glrLed == null) {
            return Result.error("未找到对应数据");
        }
        return Result.ok(glrLed);
    }
    /**
     * 导出excel
     *
     * @param request
     * @param glrLed
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, GlrLed glrLed) {
        return super.exportXls(request, glrLed, GlrLed.class, "LED屏管理");
    }
    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, GlrLed.class);
    }
    /**
     * 开关LED屏
     *
     * @return
     */
    @AutoLog(value = "开关LED屏",logType= CommonConstant.LOG_TYPE_2)
    @PostMapping(value = "/ledOpenOrClose")
    public Result<?> ledOpenOrClose(@RequestBody GlrLed glrLed) {
        //如果ID不为空
        if (StringUtil.isNotEmpty(glrLed.getIds())) {
            String[] strids = glrLed.getIds().split(",");
            String str = "";
            for (int i = 0; i < strids.length; i++) {
                if (StringUtil.isNotEmpty(str)) {
                    str = str + "," + "'" + strids[i] + "'";
                } else {
                    str = "'" + strids[i] + "'";
                }
            }
            List<GlrLed> list = glrLedService.getLedByIds(str);
            for (GlrLed led : list) {
                if (StringUtil.isNotEmpty(led.getStatus())) {
                    boolean flag = false;
                    try {
                        flag = ledCommon.OpenClose(led.getCode(), glrLed.getStatus());
                        if (flag) {
                            glrLedService.ledOpenOrClose(led.getId(), glrLed.getStatus());
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                }

            }
        }
        return Result.ok(glrLed);
    }
    /**
     * 功能描述: 获取LED屏下载资源返回的进度
     *
     * @param:
     * @return:
     * @auther: Administrator
     * @date: 2019/11/25 17:05
     */
    @PostMapping(value = "/getByJSON")
    public void getByJSON(@RequestBody JSONObject jsonParam) {
        //System.out.println(jsonParam.toJSONString());
        // 直接将json信息打印出来
        if (jsonParam.getString("progress") != null) {
            glrLedService.updateProgressByCommandId(jsonParam.getString("progress"), jsonParam.getString("commandId"));
        }
    }
    /**
     * 功能描述: 设置亮度
     *
     * @param:
     * @return:
     * @auther: Administrator
     * @date: 2020/3/12 10:23
     */
    @AutoLog(value = "设置LED屏亮度",logType= CommonConstant.LOG_TYPE_2)
    @PostMapping(value = "/setBrightnessValue")
    public Result<?> setBrightnessValue(@RequestBody GlrLed glrLed) {
        //如果ID不为空
        try {
            if (StringUtil.isNotEmpty(glrLed.getCodes())) {
                String codeArr[] = glrLed.getCodes().split(",");
                for (String code : codeArr) {
                    try {
                        boolean flag = ledCommon.setBrightness(code, glrLed.getBrightness(),glrLed.getDisabledValue());
                        if (flag) {
                            if(!glrLed.getDisabledValue()){
                                glrLedService.updateBrightnessByCodes(glrLed.getBrightness(),code);
                            }
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

            }
            return Result.ok("操作成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("操作失败");
        }
    }
    /**
     * 功能描述: 清空LED屏资源
     *
     * @param:
     * @return:
     * @auther: Administrator
     * @date: 2020/3/12 10:23
     */
    @AutoLog(value = "清空LED屏资源",logType= CommonConstant.LOG_TYPE_2)
    @PostMapping(value = "/ledClear")
    public Result<?> ledClear(@RequestBody GlrLed glrLed) {
        //如果ID不为空
        if (StringUtil.isNotEmpty(glrLed.getCodes())) {
            String codeArr[] = glrLed.getCodes().split(",");
            for (String code : codeArr) {
                try {
                    ledCommon.clearLed(code);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
        return Result.ok("操作成功");
    }
    /**
     * 功能描述: 设置时间
     *
     * @param:
     * @return:
     * @auther: Administrator
     * @date: 2020/3/12 10:23
     */
    @AutoLog(value = "同步LED屏资源",logType= CommonConstant.LOG_TYPE_2)
    @PostMapping(value = "/ledSnysTime")
    public Result<?> ledSnysTime(@RequestBody GlrLed glrLed) {
        //如果ID不为空
        if (StringUtil.isNotEmpty(glrLed.getCodes())) {
            String codeArr[] = glrLed.getCodes().split(",");
            for (String code : codeArr) {
                try {
                    ledCommon.syncTime(code);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
        return Result.ok("操作成功");
    }

    /**
     * 功能描述: 获取图片
     *
     * @param:
     * @return:
     * @auther: Administrator
     * @date: 2020/3/12 10:23
     */
    @PostMapping(value = "/getLedImgByCode")
    public Result<?> getLedImgByCode(@RequestBody GlrLed glrLed) throws Exception {
        //如果ID不为空
        if (StringUtil.isNotEmpty(glrLed.getCode())) {
            String  imgbase64=ledCommon.getLedImgByCode(glrLed.getCode());
            if(StringUtil.isNotEmpty(imgbase64)){
               return  Result.ok(imgbase64);
            }else{
                return Result.ok("操作失败");
            }
        }
        return Result.ok("操作成功");
    }
    /**
     * 功能描述: 重启LED屏
     *
     * @param:
     * @return:
     * @auther: Administrator
     * @date: 2020/3/12 10:23
     */
    @AutoLog(value = "重启LED屏",logType= CommonConstant.LOG_TYPE_2)
    @PostMapping(value = "/restartLed")
    public Result<?> restartLed(@RequestBody GlrLed glrLed) throws Exception {
        //如果ID不为空
        if (StringUtil.isNotEmpty(glrLed.getCode())) {
            Boolean  flag=ledCommon.restartLed(glrLed.getCode());
            if(flag){
                return  Result.ok("操作成功");
            }else{
                return Result.ok("操作失败");
            }
        }
        return Result.ok("操作成功");
    }

}
